package com.bamboo.msmservice.service.impl;

import com.bamboo.msmservice.service.MsmService;
import com.bamboo.msmservice.utils.MsmUtil;
import com.bamboo.msmservice.utils.RandomUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;


/**
 * @author jack.wu
 * @version 1.0
 * @date 2020-07-13
 */
@Slf4j
@Service
public class MsmServiceImpl implements MsmService {

    @Resource
    private RedisTemplate<String, String> redisTemplate;

    @Override
    public boolean sendMsm(String phone) {
        // 首先看是否已发送
        String codeCache = redisTemplate.opsForValue().get(phone);
        if (!StringUtils.isEmpty(codeCache)) {
            return true;
        }
        // 生成验证码
        String code = RandomUtil.getFourBitRandom();
        // 发送
        boolean isSuccess = MsmUtil.send(phone, code);
        if (isSuccess) {
            // 成功加入到redis
            redisTemplate.opsForValue().set(phone, code, 5, TimeUnit.MINUTES);
        }
        return isSuccess;
    }
}
